<?php

require_once "application/exception/NullPointerException.php";

/**
 * Validate class allows the use of a number of validation
 * methods, which throw exceptions if the validation does 
 * not pass
 * 
 */
class Validate{
	
	/**
	 * validates that the passed variable is not null
	 * 
	 * @throws Exception, if variable is null
	 * @return boolean
	 */
	// TODO: see if PHP5 supports overloading instead of
	// using optional parameters
	public static function notNull($input, $msg = null){
		
		// exception message
		if($msg == null)
			$msg =  "field was null, when validating for not null";
		
		if($input == null)
			throw new NullPointerException($msg);
			
		return true;
	}
	
	/**
	 * validates that the wii code is a valid wii code
	 * valid wii codes include:
	 * 
	 * "0000-0000-0000-0000"
	 * "0000000000000000"
	 * "0000 0000 0000 0000"
	 * "0000.0000.0000.0000"
	 * 
	 * TODO: this will probably incorrectly validate as a valid wii code:
	 * 0000a0000a0000a0000
	 * 
	 * @throws Exception, if variable is not a valid Wii code
	 * @return boolean
	 */
	public static function isValidWiiCode($input){

		if(preg_match("/^[0-9]{16}/", $input))
			return true; 
		
		if (preg_match("/^[0-9]{4}+.[0-9]{4}+.[0-9]{4}+.[0-9]{4}/", $input))
			return true;

		throw new Exception("wii code format is not a valid format");
	}
	
	/**
	 * validates that the friend code is a valid friend code
	 * valid friend codes include:
	 * 
	 * "0000-0000-0000"
	 * "000000000000"
	 * "0000 0000 0000"
	 * "0000.0000.0000"
	 * 
	 * or a EA Nation code
	 * 
	 * TODO: this will probably incorrectly validate as a valid friend code:
	 * 0000a0000a0000
	 * 
	 * @throws Exception, if variable is not a valid friend code
	 * @return boolean
	 */
	public static function isValidFriendCode($input, $gameId){
		
		require_once "data/dao/GameDAO.php";
		$gdao = new GameDAO();
		$manufacturer = $gdao->getGame($gameId)->getManufacturer();
		
		// EA Nation friend codes - 4-16 characters and/or numbers
		if ($manufacturer == "Electronic Arts" || $manufacturer == "Activision"){
			if(preg_match("/^[A-Za-z0-9]{3}.+/", $input))
				return true;
		}
		
		if(preg_match("/^[0-9]{12}/", $input))
			return true;
			
		if(preg_match("/^[0-9]{4}+.[0-9]{4}+.[0-9]/", $input))
			return true;
			
		throw new Exception("friend code format is not a valid format");
	}
}
?>